import {Table, Input, Button, Popconfirm, Form} from 'antd';
import React from "react";
import ExtraCard from "../ExtraCard";

const EditableContext = React.createContext();

const EditableRow = ({form, index, ...props}) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({editing}, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const {record, handleSave} = this.props;
    console.log('recordd', record);
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.key]) {
        return;
      }
      this.toggleEdit();
      console.log('valuesvalues', values);
      _.map(values, (value, key) => {
        record[key] = value;
      });
      handleSave({...record, ...values});
    });
  };

  renderCell = form => {
    this.form = form;
    const {children, dataIndex, record, title} = this.props;
    const {editing} = this.state;
    return editing ? (
      <Form.Item style={{margin: 0}}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{paddingRight: 24}}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    const {dataSource = [], columns = []} = this.props;
    this.state = {};
    this.state.dataSource = dataSource;
    this.state.count = dataSource.length+1;
    console.log('data source', dataSource);
    _.map(columns, col => {
      col.editable = true;
      col.dataIndex = col.key;
    });
    this.state.columns = [
      //   {
      //   title: '序号',
      //   dataIndex: 'no',
      //   key: 'no',
      //   editable: true
      // },
      ...columns];
    this.state.columns.push(
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record.key)}>
              <a>删除</a>
            </Popconfirm>
          ) : null,
      },
    );

  }

  componentWillUnmount(props) {
    const {callback} = this.props;
    callback(this.state);
  }

  handleDelete = key => {
    const dataSource = [...this.state.dataSource];
    this.setState({dataSource: dataSource.filter(item => item.key !== key)});
    const {callback} = this.props;
    callback(this.state);
  };

  handleAdd = () => {
    const {count = 1, dataSource, columns} = this.state;
    const newData = {
      key: count,
    };
    _.map(columns, item => {
      const {key} = item;
      newData[key] = '新增';
    });

    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
    const {callback} = this.props;
    callback(this.state);
  };

  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);

    const item = newData[index];
    console.log('itemitem', item);
    newData.splice(index, 1, {
      ...item,
      ...row,
    });

    this.setState({dataSource: newData});
    console.log("savee", this.state);
    const {callback} = this.props;
    callback(this.state);
  };

  render() {
    const {dataSource} = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.state.columns.map(col => {
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div>
        <Button onClick={this.handleAdd} type="primary" style={{marginBottom: 16}}>
          添加
        </Button>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
        />
      </div>
    );
  }
}


export default EditableTable;
